/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.header;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.sip.InvalidArgumentException;
import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class TimeStampHeaderParser extends HeaderParserBase<TimeStampHeaderImpl> {
    private final static Log logger = LogFactory.getLog(TimeStampHeaderParser.class);

    protected Log getLogger() {
        return logger;
    }

    public TimeStampHeaderImpl createLazily(byte[] data, int start, int end) {
        return new TimeStampHeaderImpl(data, start, end);
    }

    public TimeStampHeaderImpl[] parse(TimeStampHeaderImpl header, byte[] data, int start, int end) throws ParseException {
        if (header == null) header = new TimeStampHeaderImpl();
        final int startOfData = ByteArrayUtil.firstMissing(data, ' ', start, end);
        int endOfData = ByteArrayUtil.lastMissing(data, ' ', startOfData, end);
        if (endOfData == -1)
            fail("Cannot parse the TimeStamp header!", startOfData);
        else
            endOfData++;
        int endOfTime = ByteArrayUtil.firstOccurence(data, ' ', startOfData, endOfData);
        if (endOfTime != -1) {
            final int startOfDelay = ByteArrayUtil.firstMissing(data, ' ', endOfTime, endOfData);
            try {
                header.setTimeDelay((int) ByteArrayUtil.parseInteger(data, startOfDelay, endOfData));
            } catch (InvalidArgumentException e) {
                fail("Cannot parse the TimeStamp header!", startOfDelay);
            }
            endOfData = endOfTime;
        }
        try {
            header.setTime(ByteArrayUtil.parseInteger(data, startOfData, endOfData));
        } catch (InvalidArgumentException e) {
            fail("Cannot parse the TimeStamp header!", startOfData);
        }
        return new TimeStampHeaderImpl[]{header};
    }
}
/*
 * $Log$
 */